<!-- 定标结果确认 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo">
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime">
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="handlerId">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.handlerId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.handlerId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="handlerDeptId">
          <h-select-depart-input
            disabled
            v-model="model.handlerDeptId"
            :departName="model.hanlderDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.hanlderDeptText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-project-input-popup>
            <!-- @change="onChangeProjectName" -->
        </u-form-item>
        <u-form-item label="项目编号" prop="finalNo">
          <u--input disabled placeholder="请输入项目编号" v-model="model.finalNo"></u--input>
        </u-form-item>
        <u-form-item label="经营团队" prop="teamName">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.teamName"
            objectField="model.teamName"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="立项日期" prop="projectEstablishDate">
          <h-time-select
            disabled
            mode="datetime"
            v-model="model.projectEstablishDate"
            placeholder="请选择立项日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            disabled
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择公司"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="year">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.year"
            objectField="model.year"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="业主单位" prop="ownerUnit">
          <h-select-customer-input-popup
            disabled
            style="width: 100%"
            v-model="model.ownerUnit"
            objectField="model.ownerUnit"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
          ></h-select-customer-input-popup>
        </u-form-item>
        <u-form-item label="联系人" prop="contacts">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.contacts"
            objectField="model.contacts"
            placeholder="请选择联系人"
            border="surround"
            :dictName="cust_lxr"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="联系方式" prop="contactTel">
          <u--input disabled placeholder="请输入联系方式" v-model="model.contactTel"></u--input>
        </u-form-item>
        <u-form-item label="项目所在地址" prop="areaCode" :borderBottom="false">
          <h-select-address-input
            disabled
            style="width: 100%"
            v-model="model.areaCode"
            placeholder="请选择项目地址"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-address-input>
        </u-form-item>
        <!-- <u-form-item label="项目详细地址" prop="projectAddress" :borderBottom="false">
          <u--input placeholder="请输入项目详细地址" v-model="model.projectAddress"></u--input>
        </u-form-item> -->
        <u-form-item label="项目来源" prop="projectSource">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.projectSource"
            objectField="model.projectSource"
            placeholder="请选择项目来源"
            border="surround"
            dictName="xmly_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="预计合同额(元)" prop="estimatedContractAmount">
          <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入预计合同额"
            v-model="model.estimatedContractAmount"
          ></u--input>
        </u-form-item>
        <u-form-item label="预计合同额大写" prop="estimatedContractcapitalChineseAmount">
          <u--input disabled placeholder="请输入预计合同额大写" v-model="model.estimatedContractcapitalChineseAmount"></u--input>
        </u-form-item>
        <u-form-item label="立项事由及说明" prop="establishReason">
          <u--textarea
            disabled
            maxlength="500"
            confirm-type="send"
            v-model="model.establishReason"
            placeholder="请输入立项事由及说明"
          ></u--textarea>
        </u-form-item>
        <view class="basic-style">
          <view class="basic-title basic-border">项目附件</view>
          <view class="py-1 space-y-1" style="width: 100%">
            <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
            <h-upload-file disabled v-model="model.attachment" :isIcon="false"></h-upload-file>
            <file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
          </view>
        </view>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">任务信息</view>
        <u-form-item label="任务编号" prop="taskId" required>
          <h-select-task-input-popup
            :projectId="model.projectId"
            v-model="model.taskId"
            class="w-100"
            :disabled="!model.projectId"
            :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
            searchPlaceholder="请输入任务编号"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="onTaskIdInput"
            :customParams="{
              changeStatus: '!changing',
              distributionType: 'producting',
            }"
            @select="model.taskDescription = $event.data.taskDescription"
          ></h-select-task-input-popup>
        </u-form-item>
        <u-form-item label="业务分类" prop="categoryName">
          <u--input disabled placeholder="请输入业务分类" v-model="model.categoryName"></u--input>
        </u-form-item>
        <u-form-item label="合同占比(%)" prop="contractRate">
          <u--input disabled type="number" v-number-normal placeholder="请输入合同占比" v-model="model.contractRate"></u--input>
        </u-form-item>
        <u-form-item label="合同分配额(元)" prop="contractAmount">
          <u--input disabled type="number" v-number-normal placeholder="请输入合同分配额" v-model="model.contractAmount"></u--input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productTeam">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.productTeam"
            objectField="model.productTeam"
            placeholder="请选择生产团队"
            border="surround"
            :tdlx="2"
          />
        </u-form-item>
        <u-form-item label="任务类型" prop="taskType" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.taskType"
            objectField="model.taskType"
            placeholder="请选择任务类型"
            border="surround"
            dictName="task_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="实施部门" prop="executeDepart">
          <h-select-depart-input
            disabled
            v-model="model.executeDepart"
            :departName="model.executeDepartText"
            placeholder="请选择实施部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.executeDepartText"
            @change="onExecuteDepartInput"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="部门负责人" prop="minister">
          <h-select-person-input-popup
            muitFlag
            v-model="model.minister"
            style="width: 100%"
            placeholder="请选择部门负责人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="项目负责人" prop="projectLeading">
          <h-select-person-input-popup
            v-model="model.projectLeading"
            style="width: 100%"
            placeholder="请选择项目负责人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>

        <!-- 当任务类型为环评咨询，水保咨询时，展示本项 -->
        <template v-if="model.taskType == 1 || model.taskType == 4">
          <u-form-item label="审核工程师" prop="approvalEngineer">
            <h-select-person-input-popup
              v-model="model.approvalEngineer"
              style="width: 100%"
              placeholder="请选择审核工程师"
              searchPlaceholder="请输入"
              border="surround"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-person-input-popup>
          </u-form-item>
          <u-form-item label="审批级别" prop="approvalLevel">
            <h-select-input-tag
              class="w-100"
              v-model="model.approvalLevel"
              objectField="model.approvalLevel"
              placeholder="请选择审批级别"
              border="surround"
              dictName="approval_level"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="审批系数" prop="approvalCoefficient">
            <u--input type="number" v-number-normal placeholder="请输入审批系数" v-model="model.approvalCoefficient"></u--input>
          </u-form-item>
          <u-form-item label="行业类别" prop="industryCategory">
            <h-select-input-tag
              class="w-100"
              v-model="model.industryCategory"
              objectField="model.industryCategory"
              placeholder="请选择行业类别"
              border="surround"
              dictName="industry_category"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="行业系数" prop="industryCoefficient">
            <u--input type="number" v-number-normal placeholder="请输入行业系数" v-model="model.industryCoefficient"></u--input>
          </u-form-item>
          <u-form-item label="复杂程度" prop="complexity">
            <h-select-input-tag
              class="w-100"
              v-model="model.complexity"
              objectField="model.complexity"
              placeholder="请选择复杂程度"
              border="surround"
              dictName="industry_coefficient"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="复杂系数" prop="complexCoefficient">
            <u--input type="number" v-number-normal placeholder="请输入复杂系数" v-model="model.complexCoefficient"></u--input>
          </u-form-item>
        </template>

        <!-- 当任务类型为检验检测时，展示本项 -->
        <template v-if="model.taskType == 2">
          <u-form-item label="是否出具报告" prop="isOutReport">
            <h-select-input-tag
              class="w-100"
              v-model="model.isOutReport"
              objectField="model.isOutReport"
              placeholder="请选择是否出具报告"
              border="surround"
              dictName="YES_OR_NO"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="费用核算方式" prop="expenseAccountingMethod">
            <h-select-input-tag
              class="w-100"
              v-model="model.expenseAccountingMethod"
              objectField="model.expenseAccountingMethod"
              placeholder="请选择费用核算方式"
              border="surround"
              dictName="expense_accounting_method"
            ></h-select-input-tag>
          </u-form-item>
          <u-form-item label="说明" prop="instruction">
            <u--textarea maxlength="500" confirm-type="send" v-model="model.instruction" placeholder="请输入说明"></u--textarea>
          </u-form-item>
          <view class="basic-style">
            <view class="basic-title basic-border">任务附件</view>
            <view class="py-1 space-y-1" style="width: 100%">
              <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
              <h-upload-file v-model="model.taskFile" :isIcon="false"></h-upload-file>
              <file-list v-if="model.taskFile" v-model="model.taskFile" :isDelete="true"></file-list>
            </view>
          </view>
        </template>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目成员</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMember">新增</u-button>
        </view>

        <u-collapse>
          <u-collapse-item :title="`项目成员表单${index + 1}`" v-for="(item, index) in formData" :key="index">
            <FormInfo :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" @copy="handleCopyForm" />
          </u-collapse-item>
        </u-collapse>
        <u-popup class="form-popup" mode="right" :show="showFormModal" @close="closeFormModal" @open="openFormModal">
          <MemberForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="showFormModal = false" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">项目预算</view>
        <u-form-item label="预算工时(人天)" prop="expectWorkTime">
          <u--input type="number" disabled v-number-normal placeholder="请输入预算工时(人天)" v-model="model.expectWorkTime"></u--input>
        </u-form-item>
        <u-form-item label="人工成本(元)" prop="workCost">
          <u--input type="number" disabled v-number-normal placeholder="请输入人工成本" v-model="model.workCost"></u--input>
        </u-form-item>
        <u-form-item label="委外费(元)" prop="outsourcingFee" required>
          <u--input type="number" v-number-normal placeholder="请输入委外费" v-model="model.outsourcingFee"></u--input>
        </u-form-item>
        <u-form-item label="差旅费(元)" prop="travelFee" required>
          <u--input type="number" v-number-normal placeholder="请输入差旅费" v-model="model.travelFee"></u--input>
        </u-form-item>
        <u-form-item label="专家评审费(元)" prop="professionReviewFee" required>
          <u--input type="number" v-number-normal placeholder="请输入专家评审费" v-model="model.professionReviewFee"></u--input>
        </u-form-item>
        <u-form-item label="其他成本(元)" prop="otherCost" required>
          <u--input type="number" v-number-normal placeholder="请输入其他成本" v-model="model.otherCost"></u--input>
        </u-form-item>
        <u-form-item label="项目预算合计(元)" prop="outsourcingFee" required>
          <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="人工总成本+委外费+差旅费+专家评审费+其他成本"
            v-model="model.totalProjectBudget"
          ></u--input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">任务进度</view>
        <u-form-item label="进度模板" prop="templateId" :borderBottom="false">
          <!-- disabled -->
          <h-select-process-template-input
            style="width: 100%"
            v-model="model.templateId"
            objectField="model.templateId"
            placeholder="请选择进度模板"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @input="getTemplateList"
          ></h-select-process-template-input>
        </u-form-item>

        <u-collapse>
          <u-collapse-item :title="`任务进度${index + 1}`" v-for="(item, index) in templateDataList" :key="index">
            <u-form labelWidth="auto" disabled>
              <u-form-item :label="key" v-for="(child, key) in taskProgressFields" :key="key">
                {{ item[child] }}
              </u-form-item>
            </u-form>
          </u-collapse-item>
        </u-collapse>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">款项进度</view>
        <u-collapse>
          <u-collapse-item :title="`款项进度表单${index + 1}`" v-for="(item, index) in priceFormData" :key="index">
            <PriceFormInfo
              :item="item"
              :index="index"
              :progressVoList="templateDataList"
              @edit="handleEditPriceForm"
              @remove="handleRemovePriceForm"
              @copy="handleCopyPriceForm"
            />
          </u-collapse-item>
        </u-collapse>
        <u-popup class="form-popup" mode="right" :show="showPriceFormModal" @close="closePriceFormModal" @open="openPriceFormModal">
          <PriceForm
            :progressVoList="templateDataList"
            ref="priceForm"
            :index="index"
            @submit="handlePriceFormSubmit"
            @close="showPriceFormModal = false"
          />
        </u-popup>
        <u-form-item label="履约保证金(元)" prop="bail">
          <u--input type="number" disabled v-number-normal placeholder="请输入履约保证金" v-model="model.bail"></u--input>
        </u-form-item>
        <u-form-item label="款项节点说明" prop="paymentDesc">
          <u--textarea maxlength="500" confirm-type="send" v-model="model.paymentDesc" placeholder="请输入款项节点说明"></u--textarea>
        </u-form-item>
        <template v-if="model.bail > 0">
          <u-form-item label="是否应收" prop="isCollectionPayment">
            <h-select-input-tag
              class="w-100"
              v-model="model.isCollectionPayment"
              objectField="model.isCollectionPayment"
              placeholder="请选择是否应收"
              border="surround"
              dictName="YES_OR_NO"
            ></h-select-input-tag>
          </u-form-item>
        </template>
        <template v-if="model.isCollectionPayment == 1">
          <u-form-item label="应收日期" prop="collectionDate">
            <h-time-select
              mode="datetime"
              v-model="model.collectionDate"
              placeholder="请选择应收日期"
              border="surround"
              suffixIcon="calendar-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-time-select>
          </u-form-item>
        </template>
      </view>

      <view class="space-x-1 mt-1 px-1 pb-1" style="display: flex">
        <u-button type="primary" text="保存提交" :loading="loading" @click="onSubmit"></u-button>
        <u-button type="primary" text="保存草稿" :loading="loading" @click="onDraft"></u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { erpProgressTemplateDtList } from '@/api/index'
import { gainBillNo, add, info, queryPageList } from '@/api/project/ErpProgressTaskChangeListForm'
import http from '@/utils/request/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import MemberForm from './components/MemberForm.vue'
import FormInfo from './components/MemberFormInfo.vue'
import PriceForm from './components/PriceForm.vue'
import PriceFormInfo from './components/PriceFormInfo.vue'
export default {
  name: 'ErpProgressTaskDistributionForm',
  components: {
    fileList,
    MemberForm,
    FormInfo,
    PriceForm,
    PriceFormInfo,
  },
  data() {
    return {
      taskProgressFields: {
        节点名称: 'nodeName',
        节点进度: 'nodeProgress',
        完成状态: 'taskCompleteStatus_dictText',
        完成时间: 'completeTime',
      },
      templateDataList: [],
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=0',
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      showPriceFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      // formData: [
      //   {
      //     id: 411283512599,
      //     materialBillId: 'WL01343',
      //     brand: '农夫山泉',
      //     specification: '6L',
      //     amount: '6',
      //     provisionSmall: '1535177002383859714',
      //     materialName: '1627503793494896641',
      //     referencePrice: null,
      //     unit: '4',
      //     budgetAmount: '12',
      //   },
      // ],
      formData: [],
      // formData: [
      //   {
      //     expectWorkTime: 1.5,
      //     projectMember_dictText: '张鹏',
      //     dayCost: 137.01,
      //     contractAmount: 2000,
      //     laborCost: 806.17,
      //     contractRate: 8.89,
      //     id: '1658066715907563521',
      //     projectMember: '1632987084150865922',
      //     projectPerformance: 600.66,
      //   },
      //   {
      //     expectWorkTime: 6.6,
      //     projectMember_dictText: '齐乃彬',
      //     dayCost: 238.16,
      //     contractAmount: 2000,
      //     laborCost: 2272.52,
      //     contractRate: 8.89,
      //     id: '1658066715936923649',
      //     projectMember: '1633259245298053122',
      //     projectPerformance: 700.66,
      //   },
      //   {
      //     expectWorkTime: 2.4,
      //     projectMember_dictText: '杨璐璐',
      //     dayCost: 152.18,
      //     contractAmount: 500,
      //     laborCost: 665.23,
      //     contractRate: 2.22,
      //     id: '1658066715962089474',
      //     projectMember: '1633674894671409153',
      //     projectPerformance: 300,
      //   },
      //   {
      //     expectWorkTime: 9,
      //     projectMember_dictText: '张冰倩',
      //     dayCost: 142.07,
      //     contractAmount: 18000,
      //     laborCost: 1286.63,
      //     contractRate: 80,
      //     id: '1658066715987255297',
      //     projectMember: '1631576319711838209',
      //     projectPerformance: 8,
      //   },
      // ],
      priceFormData: [],
      // priceFormData: [
      //   {
      //     nodeName: '款项一',
      //     isRelatedTaskNode_dictText: '是',
      //     isRelatedTaskNode: '1',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716658343937',
      //     taskNodeId_dictText: '节点2',
      //     sortOrder: 1,
      //     isCollectionPayment: '0',
      //     nodeDesc: '这是款项一的节点说明。',
      //     id: '1657935704381038593',
      //     paymentMoney: 20000,
      //     projectId: null,
      //     taskNodeId: '16841483915486246409947902610665',
      //     paymentDesc: null,
      //   },
      //   {
      //     nodeName: '款项二',
      //     isRelatedTaskNode_dictText: '否',
      //     isRelatedTaskNode: '0',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716691898370',
      //     taskNodeId_dictText: null,
      //     sortOrder: 2,
      //     isCollectionPayment: '0',
      //     nodeDesc: '13899 【项目管理-任务管理-任务委托-三期】新增页面，项目成员、项目预算模块新增字段，置灰不可编辑',
      //     id: '1657935704418787329',
      //     paymentMoney: 30000,
      //     projectId: null,
      //     taskNodeId: null,
      //     paymentDesc: null,
      //   },
      //   {
      //     nodeName: '款项三',
      //     isRelatedTaskNode_dictText: '是',
      //     isRelatedTaskNode: '1',
      //     delFlag: null,
      //     isCollectionPayment_dictText: '否',
      //     collectionDate: null,
      //     isRelatedTask: '1',
      //     isRelatedTask_dictText: '是',
      //     finalId: '1658066716721258498',
      //     taskNodeId_dictText: '节点三',
      //     sortOrder: 3,
      //     isCollectionPayment: '0',
      //     nodeDesc: '这是款项手机',
      //     id: '1657935704452341761',
      //     paymentMoney: 40000,
      //     projectId: null,
      //     taskNodeId: '16841483915489671058063991079684',
      //     paymentDesc: null,
      //   },
      // ],
      model: {
        applyType: 1,
        billNo: '',
        createTime: '',
        handlerId: '',
        handlerDeptId: '',
        projectId: '',
        finalNo: '',
        teamName: '',
        undertaker: '',
        projectEstablishDate: '',
        signUnit: '',
        year: '',
        ownerUnit: '',
        contacts: '',
        contactTel: '',
        areaCode: '',
        projectAddress: '',
        projectSource: '',
        estimatedContractAmount: '',
        estimatedContractcapitalChineseAmount: '',
        establishReason: '',
        taskId: '',
        categoryName: '',
        contractRate: '',
        contractAmount: '',
        productTeam: '',
        taskType: '',
        executeDepart: '',
        minister: '',
        projectLeading: '',
        taskFile: null,
        templateId: '',
        purchaseFile: null,
      },
      rules: {
        projectId: [{ required: true, message: '请选择项目名称!', pattern: '[^ \x22]+' }],
        taskType: [{ required: true, message: '请选择任务类型!' }],
        taskId: [{ required: true, message: '请选择任务编号!' }],
        outsourcingFee: [{ required: true, message: '请输入委外费!' }],
        travelFee: [{ required: true, message: '请输入差旅费!' }],
        professionReviewFee: [{ required: true, message: '请输入专家评审费!' }],
        otherCost: [{ required: true, message: '请输入其他成本!' }],
        collectionDate: [{ required: true, message: '请选择应收日期!' }],
      },
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  onReady() {
    this.$refs.projectSelect.$on('change', (event) => {
      this.onChangeProjectName(event)
    })
  },
  onUnload() {
    this.$off('change')
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
    }
    // this.initBuyerInfo()
  },
  computed: {
    ...mapState(['userInfo']),
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    // 总工时
    expectWorkTime() {
      if (!this.formData || !this.formData.length) {
        return 0
      }

      return this.formData.reduce((total, cur) => {
        return total + (Number(cur.expectWorkTime) || 0)
      }, 0)
    },
    // 总人工成本
    workCost() {
      if (!this.formData || !this.formData.length) {
        return 0
      }
      return this.formData.reduce((total, cur) => {
        return total + (Number(cur.laborCost) || 0)
      }, 0)
    },
    // 总花费
    totalProjectBudget() {
      const { outsourcingFee, travelFee, professionReviewFee, otherCost } = this.model
      return this.expectWorkTime + this.workCost + (outsourcingFee || 0) + (travelFee || 0) + (professionReviewFee || 0) + (otherCost || 0)
    },
  },
  methods: {
    getFieldsValue(key, value) {
      if (key === '是否关联任务节点' || key === '是否关联进度') {
        return value === '1' ? '是' : '否'
      }
      return value
    },
    // 选择项目名称
    async onChangeProjectName(event) {
      if (!event) {
        this.$set(this.model, 'projectName', undefined) // 项目名称
        this.$set(this.model, 'bail', undefined) // 保证金
        this.$set(this.model, 'finalNo', undefined) // 项目编号
        this.$set(this.model, 'teamName', undefined) // 经营团队
        this.$set(this.model, 'undertaker', undefined) // 项目承接人
        this.$set(this.model, 'projectEstablishDate', undefined) // 立项日期
        this.$set(this.model, 'signUnit', undefined) // 签订单位
        this.$set(this.model, 'year', undefined) // 业绩归属年度
        this.$set(this.model, 'ownerUnit', undefined) // 业主单位
        this.$set(this.model, 'contacts', undefined) // 联系人
        this.$set(this.model, 'contactTel', undefined) // 联系方式
        this.$set(this.model, 'areaCode', undefined) // 项目所在地址
        this.$set(this.model, 'projectAddress', undefined) // 项目所在详细地址
        this.$set(this.model, 'projectSource', undefined) // 项目来源
        this.$set(this.model, 'estimatedContractAmount', undefined) // 预计合同额
        this.$set(this.model, 'estimatedContractcapitalChineseAmount', undefined) // 预计合同额大写
        this.$set(this.model, 'establishReason', undefined) // 立项事由及说明
        this.$set(this.model, 'attachment', undefined) // 项目附件

        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'categoryCode', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        this.$set(this.model, 'taskId', undefined) // 任务编号
        this.priceFormData = [] // 清空款项进度
        return false
      }
      // this.queryPaymentListByProjectId(event.id) // 获取款项进度列表
      // this.queryPaymentNodeListByMainId(event.id)
      this.getQueryByEntity(event.id) // 获取履约保证金
      // this.queryTaskNodeListByMainId(event.id) //  获取任务进度
      this.$set(this.model, 'projectName', event.projectName) // 项目名称
      this.$set(this.model, 'finalNo', event.finalNo) // 项目编号
      this.$set(this.model, 'teamName', event.teamName) // 经营团队
      this.$set(this.model, 'undertaker', event.undertaker) // 项目承接人
      this.$set(this.model, 'projectEstablishDate', event.projectEstablishDate) // 立项日期
      this.$set(this.model, 'signUnit', event.signUnit) // 签订单位
      this.$set(this.model, 'year', event.year) // 业绩归属年度
      this.$set(this.model, 'ownerUnit', event.ownerUnit) // 业主单位
      this.$set(this.model, 'contacts', event.contacts) // 联系人
      this.$set(this.model, 'contactTel', event.contactTel) // 联系方式
      this.$set(this.model, 'areaCode', event.areaCode) // 项目所在地址
      this.$set(this.model, 'projectAddress', event.projectAddress) // 项目所在详细地址
      this.$set(this.model, 'projectSource', event.projectSource) // 项目来源
      this.$set(this.model, 'estimatedContractAmount', event.estimatedContractAmount) // 预计合同额
      this.$set(this.model, 'estimatedContractcapitalChineseAmount', event.estimatedContractcapitalChineseAmount) // 预计合同额大写
      this.$set(this.model, 'establishReason', event.establishReason) // 立项事由及说明
      this.$set(this.model, 'attachment', event.attachment) // 项目附件
      this.cust_lxr = "erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id='" + event.ownerUnit + "'"

      this.$set(this.model, 'categoryName', undefined) // 业务分类
      this.$set(this.model, 'categoryCode', undefined) // 业务分类
      this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
      this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

      this.$set(this.model, 'productTeam', undefined) // 生产团队
      this.$set(this.model, 'taskId', undefined) // 任务编号
    },

    // 选择任务编号
    onTaskIdInput({ data: event }) {
      if (!event) {
        this.$set(this.model, 'categoryName', undefined) // 业务分类
        this.$set(this.model, 'categoryCode', undefined) // 业务分类
        this.$set(this.model, 'contractRate', undefined) // 合同占比(%)
        this.$set(this.model, 'contractAmount', undefined) // 合同分配额(元)

        this.$set(this.model, 'productTeam', undefined) // 生产团队
        return false
      }
      this.getTaskNodeList(1, '', this.model.projectId, event.id) // 获取任务进度
      this.getPaymentList(1, '', this.model.projectId, event.id) // 获取款项进度
      this.getMemberList(1, '', this.model.projectId, event.id) // 查看成员
      this.getTemplateId(this.model.taskId)

      this.$set(this.model, 'categoryName', event.categoryName) // 业务分类
      this.$set(this.model, 'categoryCode', event.categoryCode) // 业务分类
      this.$set(this.model, 'contractRate', event.contractRate) // 合同占比(%)
      this.$set(this.model, 'contractAmount', event.contractAmount) // 合同分配额(元)

      this.$set(this.model, 'productTeam', event.productTeam) // 生产团队

      this.$set(this.model, 'outsourcingFee', event.outsourcingFee) // 委外费
      this.$set(this.model, 'travelFee', event.travelFee) // 差旅费
      this.$set(this.model, 'professionReviewFee', event.professionReviewFee) // 专家评审费
      this.$set(this.model, 'otherCost', event.otherCost) // 其他成本

      this.$set(this.model, 'taskType', event.taskType) // 任务类型
      this.$set(this.model, 'executeDepart', event.executeDepart) // 实施部门
      this.$set(this.model, 'minister', event.minister) // 部门负责人
      this.$set(this.model, 'projectLeading', event.projectLeading) // 项目负责人
    },

    getQueryByEntity(id) {
      var params = {
        preProjectId: id,
        feeCategory: '2',
        bpmStatus: '3',
      }
      // 查看项目保证金
      http.get('/api/erp/finance/deposit/erpFinanceProjectDepositBill/queryByEntity', params).then((res) => {
        if (res.success) {
          let data = res.result
          this.$set(this.model, 'bail', data.remittanceAmount)
          // this.$set(this.validatorRules, 'collectionDate', [{ required: true, message: '请选择应收日期!' }]);
          // this.$set(this.validatorRules, 'paymentDesc', [{ required: true, message: '请填写款项节点说明!' }]);
        } else {
          this.$set(this.model, 'bail', undefined)
          // this.$delete(this.validatorRules, 'collectionDate');
          // this.$delete(this.validatorRules, 'paymentDesc');
        }
      })
    },

    // 获取款项进度列表
    queryPaymentListByProjectId(taskId) {
      this.priceFormData = []
      http.get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskPaymentList', { taskId }).then((res) => {
        if (res.success) {
          this.priceFormData = res.result
        }
      })
    },
    // 编辑获取款项进度列表
    queryPaymentNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.priceFormData = []
      this.progressNodeVoLoading = true
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryPaymentNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.priceFormData = res.result
          } else {
            this.queryPaymentListByProjectId(this.model.taskId) // 获取款项进度列表
          }
        })
        .finally(() => {
          this.progressNodeVoLoading = false
        })
    },
    // 编辑获取任务进度列表
    queryTaskNodeListByMainId(id) {
      if (!id) {
        return false
      }
      this.templateLoading = true
      this.templateDataList = []
      http
        .get('/api/erp/omc/task/erpOmcTaskDistribution/queryTaskNodeListByMainId', { id })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 选择实施部门
    onExecuteDepartInput(item) {
      if (!item.minister) {
        this.$set(this.model, 'minister', undefined)
        return false
      }
      // 赋值部门负责人
      http.get('/api/erpmng/sys/api/queryUsersByUsernames', { usernames: item[0].minister }).then((res) => {
        var idsArr = []
        var ids = ''
        if (res && res.length) {
          res.map((value) => {
            idsArr.push(value.empId)
          })
        }
        ids = idsArr.toString()
        this.$set(this.model, 'minister', ids)
      })
    },

    // 选择进度模板
    getTemplateList(data) {
      erpProgressTemplateDtList({ mainId: data.id }).then((res) => {
				if (res.success) {
					// 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
					let isAddChildNode = data.isAddChildNode
					this.templateDataList = res.result.map((item, index) => {
						item.id = this.getRandomNum()
						if (index === res.result.length - 1) {
							item.isAddChildNode = '0'
						} else {
							item.isAddChildNode = isAddChildNode
						}
						return item
					})
				}
      })
    },

    // 获取唯一随机数
    getRandomNum() {
      let date = new Date().valueOf() // 获取时间戳
      let txt = '1234567890' // 生成的随机机器码
      let len = 19 // 机器码有多少位
      let pwd = '' // 定义空变量用来接收机器码
      for (let i = 0; i < len; i++) {
        pwd += txt.charAt(Math.floor(Math.random() * txt.length)) // 循环机器码位数随机填充
      }
      return date + pwd
    },
    // 款项进度完善
    PerfectTaskChange(val) {
      this.priceFormData.forEach((it, i) => {
        if (it.id === val.id) {
          this.priceFormData.splice(i, 1, val)
        }
      })
    },
    // 获取任务进度
    getTaskNodeList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryTaskNodeList', { handlerType, id, projectId, taskId, isChild: '0' })
        .then((res) => {
          if (res.success) {
            this.templateDataList = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取款项进度
    getPaymentList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryPaymentList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.priceFormData = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },

    // 查看成员列表
    getMemberList(handlerType, id, projectId, taskId) {
      http
        .get('/api/erp/omc/task/erpOmcTaskDistributionChange/queryMemberList', { projectId, id, taskId, handlerType })
        .then((res) => {
          if (res.success) {
            this.formData = res.result
          }
        })
        .finally(() => {
          this.templateLoading = false
        })
    },
    // 获取任务进度模板
    getTemplateId(id) {
      queryPageList({ id }).then((res) => {
        if (res.success) {
          var event = res.result.records[0]
          this.$set(this.model, 'templateId', event.templateId)
          this.$set(this.model, 'templateName', event.templateName)
        }
      })
    },
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
      // this.initBuyerInfo()
    },
    // ----------不同子表分界线----------
    handleCopyPriceForm([item, index]) {
      this.priceFormData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditPriceForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showPriceFormModal = true
    },
    handleRemovePriceForm(item) {
      this.priceFormData = this.priceFormData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openPriceFormModal() {
      this.$refs.priceForm.basicForm = this.basicForm
    },
    addPriceForm() {
      this.index = null
      this.showPriceFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handlePriceFormSubmit([data, index]) {
      this.showPriceFormModal = false
      if (typeof index === 'number') {
        this.$set(this.priceFormData, index, data)
      } else {
        this.priceFormData.push(data)
      }
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'RWBG', subSystemCode: '05' })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.handlerId = this.userInfo.empId //当前登录人
      this.model.handlerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      for (const key in data) {
        if (Object.hasOwnProperty.call(this.model, key)) {
          this.model[key] = data[key]
        }
      }
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.model.projectBudget >= 10000) {
          this.$u.toast('当前采购总金额大于等于10000元，请走招标采购申请单！')
          return Promise.reject('当前采购总金额大于等于10000元，请走招标采购申请单！')
        }
        if (!this.formData.length) {
          this.$u.toast('请添加物资明细信息！')
          return Promise.reject('请添加物资明细信息！')
        }
        return Promise.resolve()
      })
    },
    async onSubmit() {
      await this.validateForm()

      try {
        this.loading = true
        const response = await add({
          ...this.model,
          distributionDtList: this.formData,
          progressNodeVoList: this.priceFormData,
          progressVoList: this.templateDataList.map((i) => {
            return {
              ...i,
              finalId: i.id,
            }
          }),
        })
        this.$u.toast(response.message)
        if (response.success) {
          setTimeout(
            () =>
              uni.switchTab({
                url: '/pages/home/home',
              }),
            1500,
          )
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      await this.validateForm()
    },
  },
  watch: {
    expectWorkTime(val) {
      this.model.expectWorkTime = val
    },
    workCost(val) {
      this.model.workCost = val
    },
    totalProjectBudget(val) {
      this.model.totalProjectBudget = val
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
